package com.souvc.weixin.copyArticle;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.souvc.weixin.util.CommonUtil;

import net.sf.json.JSONObject;

public class Copy {
	 // 获取img标签正则
    private static final String IMGURL_REG = "<img.*src=(.*?)[^>]*?>";
  
         public static String copyTowx(String URL){
        	 Document doc;
        	 
        	 String content = null;
        	 String result = null;
        	 
        	 try {
				 doc = Jsoup.connect(URL).get();
				 Elements c = doc.select("div.xiangqingPag h2,div.xiangqingPag h2 + div");
				
				  content = c.toString();
				  result = content.replace("\"", "'");
			     
			} catch (IOException e) {
				
				e.printStackTrace();
			}
      
        	 return result;        	 
         }
         public static List<String> copyArticle(String URL){
        	 List<String> ls =null;
              Document doc;
        	  String title =null;
              String HTML = null;
        	 try {
        		 
				 doc = Jsoup.connect(URL).get();
				  Elements b = doc.select("h2.title");
				  Elements c = doc.select("div.content");
				  title = b.text();
				  HTML = c.toString();
				 
				 List<String> imgUrl = Copy.getImageUrl(HTML);
				 //获取图片src地址
		            List<String> imgSrc =Copy.getImageSrc(imgUrl);
		            //下载图片
		           ls = Copy.DownloadAndUpload(imgSrc,HTML,title);
				  System.out.println(ls.get(0));
				  System.out.println(ls.get(1));
			     
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			return ls;
      
        	
         }
         public static List<String> getImageUrl(String html) {
        	 Matcher matcher=Pattern.compile(IMGURL_REG).matcher(html);
             List<String>listimgurl=new ArrayList<String>();
             while (matcher.find()){
                 listimgurl.add(matcher.group());
             }
             return listimgurl;
		}
       //获取ImageSrc地址
         public static List<String> getImageSrc(List<String> listimageurl){
             List<String> listImageSrc=new ArrayList<String>();
             for (String url : listimageurl) {
            	 Document doc = Jsoup.parse(url);
            	 Elements link = doc.select("img");
            	 String src = link.attr("src");
            	 listImageSrc.add(src);
			}
            
             return listImageSrc;
         }
       //下载图片
         public static List<String> DownloadAndUpload(List<String> listImgSrc,String html,String title) {
        	 
        	 List<String> list = new ArrayList<String>();//用来储存标题,替换src后的正文
        	 try {
                 //开始时间
                 Date begindate = new Date();
                 int i = 1;
                 for (String url : listImgSrc) {
                     //开始时间
                	 int count = i++;
                     Date begindate2 = new Date();
                     String imageName =""+count+"" ;
                     URL uri = new URL(url);
                     InputStream in = uri.openStream();
                     FileOutputStream fo = new FileOutputStream(new File("D:/img/"+imageName+".jpg"));//文件输出流
                     byte[] buf = new byte[1024];
                     int length = 0;
                     System.out.println("开始下载:" + url);
                     while ((length = in.read(buf, 0, buf.length)) != -1) {
                         fo.write(buf, 0, length);
                     }
                     //关闭流
                     in.close();
                     fo.close();
                     System.out.println(imageName + "下载完成");
                     //结束时间
                     Date overdate2 = new Date();
                     double time = overdate2.getTime() - begindate2.getTime();
                     System.out.println("耗时：" + time / 1000 + "s");
                 }
                 Date overdate = new Date();
                 double time = overdate.getTime() - begindate.getTime();
                 System.out.println("总耗时：" + time / 1000 + "s");
               //开始上传
                List<String> slist = new ArrayList<String>();
                File dir = new File(CommonUtil.Path);
                File [] fs = dir.listFiles();
                for (File file : fs) {
                	 if(file.exists() && !file.isDirectory() && file.getName().endsWith(".jpg")){
                		 
                     	JSONObject im = CommonUtil.UploadImage("image", file.getAbsolutePath());
                     	String src =im.getString("url");
                     	slist.add(src);
                     } else {
                    	 throw new Exception("图片未找到!!!!");
                     }
				}
                Document doc = Jsoup.parse(html);
           	    Elements link = doc.select("img");
           	    int s=0;
           	    for (Element element : link) {
           	    	element.attr("src", slist.get(s++));
				}
           	    
           	    String Article = doc.toString();
           	    String result = Article.replace("\"", "'");
           	    //替换双引号
           	    list.add(title);
           	    list.add(result);
           	    
           	 
             } catch (Exception e) {
                 System.out.println("下载失败");
             }
			return list;
         }
		public static void main(String[] args) {
			Copy.copyArticle("http://www.bishijie.com/shendu_4382");
			 
        	 
		}
}
